const process = require("process"),
    multiparty = require('multiparty');

const uploadServices = require('./../services/upload');

const index = (req, res, next) => {
    res.render('upload');
};

const {md5PassWord} = require(`./../../config`);


const upload = (req, res) => {
    const {headers} = req;

    const Authorization = headers[`authorization`];

    //身份认证
    if (Authorization !== md5PassWord) {
        return res.send({
            code: 304,
            message: `Authorization error!`
        });
    }

    const uploadDir = `${process.cwd()}/upload`;

    //内容大小
    const uploadSize = headers[`content-length`] / 1000 / 1000;

    const maxFilesSize = 30; //5M

    if (uploadSize > maxFilesSize) {
        return res.send({
            code: 413,
            message: `上传文件不能大于${maxFilesSize}M`
        })
    }

    const form = new multiparty.Form({
        uploadDir: uploadDir,
        encoding: "utf-8",
        keepExtensions: true,
        maxFilesSize: maxFilesSize * 1024 * 1024,
        maxFields: 20
    });

    form.parse(req, (error, fields, files) => {
        if (!!error) {
            const {statusCode} = error;
            return res.send({
                code: statusCode,
                message: `文件上传失败!`
            });
        }
        uploadServices.qiniuUpload(files.file).then(ret => {
            res.send({
                code: 200,
                errno:0,
                data: ret
            });
        }).catch(error => {
            res.send({
                code: 500,
                errno:1,
                message: error
            })
        });
    });

};


exports.index = index;

exports.upload = upload;